// hello
package mysql

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type User struct {
	gorm.Model
	Status uint
	Email  string
	Pwd    string
	Permission bool
}
var users []User

//find the user if is can signin
func SqlSignIn(meg *User) (bool, error) {
	db, err := gorm.Open("mysql", "root:123456@(localhost)/db?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		return false, err
	}
	db.AutoMigrate(&User{})
	var temp User
	fmt.Printf("user:%s %s\n", meg.Email, meg.Pwd)
	temp.ID = 0
	db.Where("Email = ? AND Pwd = ? AND Status = ?", meg.Email, meg.Pwd, 2).Find(&temp)
	if temp.ID != 0 {
		return true, nil
	}
	return false, nil
}

//create a new client in databaes
func SqlCreate(meg *User) (bool, error) {
	db, err := gorm.Open("mysql", "root:123456@(localhost)/db?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		return false, err
	}
	db.AutoMigrate(&User{})
	db.Create(meg)
	return true, nil
}

//change the status of client
func SqlChange(msg *User) (bool, error) {
	db, err := gorm.Open("mysql", "root:123456@(localhost)/db?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		return false, err
	}
	db.AutoMigrate(&User{})
	db.Model(&User{}).Where("email=?", msg.Email).Update("status", msg.Status).Update("pwd", msg.Pwd)
	return true, nil
}

//get all cli
func SqlGetALL()([]User,int64,error){
	db, err := gorm.Open("mysql", "root:123456@(localhost)/db?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		return users,0, err
	}
	db.AutoMigrate(&User{})
	result:=db.Find(&users)
	return users,result.RowsAffected,result.Error; 
}

//sql judge if super
func SqlJudge(email string)(bool,error){
	db, err := gorm.Open("mysql", "root:123456@(localhost)/db?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		return false,err;
	}
	db.AutoMigrate(&User{})
	var temp User
	temp.ID = 0
	db.Where("Email = ? AND Status = ? AND Permission = ?",email,2,true).Find(&temp)
	if temp.ID==0{
		return false,nil;
	}
	return true,nil;
}

//delete 
func SqlDelete(email string)(bool,error){
	db, err := gorm.Open("mysql", "root:123456@(localhost)/db?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		return false,err;
	}
	db.AutoMigrate(&User{})
	db.Where("Email=?",email).Delete(User{});
	return true,nil;
}
// find
func SqlFind(email string)(bool,error){
	db, err := gorm.Open("mysql", "root:123456@(localhost)/db?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		return false,err;
	}
	db.AutoMigrate(&User{})
	var temp User
	temp.ID = 0
	db.Where("Email = ?",email).Find(&temp)
	if temp.ID != 0 {
		return true, nil
	}
	return false, nil

}
